#include "ImageHelper.h"
#include "swf/SWFTag.h"
#include <QImageWriter>
#include <QBuffer>
#include "QtZlib/zlib.h"

TagDefineBits* ImageHelper::createDefineBits( QImage* image )
{
	return nullptr;
}

TagDefineBitsJPEG3* ImageHelper::createDefineBitsJPEG3( QImage* image )
{
	uchar* bits = image->bits();
	size_t imageSize = image->width() * image->height();
	TagDefineBitsJPEG3* tag = new TagDefineBitsJPEG3();

	char* alphaData = (char*)malloc(imageSize);
	int alphaIndex = 0;
	for (size_t i = 0; i < imageSize; ++i)
	{
		char a = bits[i * 4 + 3];
		//char r = bits[i + 2];
		//char g = bits[i + 1];
		//char b = bits[i + 0];
		alphaData[alphaIndex++] = a;
	}
	char* dest = (char*)malloc(imageSize);
	z_uLongf destLen;
	compress((z_Bytef*)dest, &destLen, (z_Bytef*)alphaData, (z_uLongf)imageSize);

	tag->alphaData.copy(dest, destLen);
	free(alphaData);

	//convert to jpeg
	QImage jpegImage = image->convertToFormat(QImage::Format_RGB888);
	QBuffer buffer;
	QImageWriter writer(&buffer, "jpeg");
	writer.write(jpegImage);
	QByteArray arr = buffer.data();
	tag->imageData.copy(arr.data(), arr.size());

	return tag;
}

